<?php
/**
 * 收藏逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

use app\common\logic\LogicBase;

class Favorite extends LogicBase
{
    /**
     * 关注商品
     */
    public function followProduct($data = [])
    {
        // 验证参数
        if (empty($data['user_id']) || empty($data['product_id'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        // 检查是否已关注
        $existWhere = [
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id']
        ];
        
        $exist = $this->modelUserFollow->getInfo($existWhere);

        // 添加关注记录
        $insertData = [
            'id' => !empty($exist['id']) ? $exist['id'] : null,
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id'],
            'status' => 1
        ];

        $result = $this->modelUserFollow->setInfo($insertData);
        if ($result) {
            return [RESULT_SUCCESS, '关注成功'];
        } else {
            return [RESULT_ERROR, '关注失败'];
        }
    }

    /**
     * 取消关注商品
     */
    public function unfollowProduct($data = [])
    {
        // 验证参数
        if (empty($data['user_id']) || empty($data['product_id'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        $where = [
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id']
        ];

        $result = $this->modelUserFollow->deleteInfo($where);
        if ($result !== false) {
            return [RESULT_SUCCESS, '取消关注成功'];
        } else {
            return [RESULT_ERROR, '取消关注失败'];
        }
    }

    /**
     * 检查关注状态
     */
    public function checkFollowStatus($data = [])
    {
        // 验证参数
        if (empty($data['user_id']) || empty($data['product_id'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        $where = [
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id'],
            'status' => 1
        ];

        $exist = $this->modelUserFollow->getInfo($where);
        
        return !empty($exist) ? true : false;
    }

    /**
     * 获取关注列表
     */
    public function getFollowList($data = [], $paginate = DB_LIST_ROWS)
    {
        // 验证参数
        if (empty($data['user_id'])) {
            return [];
        }

        $this->modelUserFollow->alias('uf');

        $where = ['user_id' => $data['user_id']];
        !empty($data['category']) && $where['p.category'] = $data['category'];
        $where['p.status'] = 1;
        
        // 设置关联查询（参考商品列表图片处理，使用picture表path作为cover）
        $this->modelUserFollow->join = [
            [SYS_DB_PREFIX . 'product p', 'p.id = uf.product_id', 'LEFT'],
            [SYS_DB_PREFIX . 'picture pic', 'pic.id = p.cover_id', 'LEFT']
        ];

        $field = 'uf.*, p.*, pic.path as cover';
        $order = 'uf.create_time desc';

        $list = $this->modelUserFollow->getList($where, $field, $order, $paginate);
        // 参考商品模型，补充涨跌幅度与趋势等派生字段
        if (!empty($list)) {
            foreach ($list as $k => $item) {
                // 计算价格变化
                $item['change_rate'] = $item['change_rate'] !== null ? round($item['change_rate'], 2) : null;
                $item['change_amount'] = $item['change_amount'] !== null ? round($item['change_amount'], 2) : null;
                $item['price_trend'] = $item['change_rate'] > 0 ? 'up' : ($item['change_rate'] < 0 ? 'down' : 'flat');
                
                // 重新赋值修改后的数据
                $list[$k] = $item;
            }
        }

        return $list;
    }

    /**
     * 设置价格提醒
     */
    public function setPriceAlert($data = [])
    {
        // 验证参数
        if (empty($data['user_id']) || empty($data['product_id']) || empty($data['target_price'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        // 检查是否已设置提醒
        $existWhere = [
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id']
        ];
        
        $exist = $this->modelPriceAlert->getInfo($existWhere);
        
        $alertData = [
            'user_id' => $data['user_id'],
            'product_id' => $data['product_id'],
            'target_price' => $data['target_price'],
            'alert_type' => $data['alert_type'] ?? 1, // 1:低于 2:高于
            'is_active' => 1,
            'update_time' => time()
        ];

        if ($exist) {
            // 更新现有提醒
            $result = $this->modelPriceAlert->updateInfo($existWhere, $alertData);
        } else {
            // 创建新提醒
            $alertData['create_time'] = time();
            $result = $this->modelPriceAlert->updateInfo([], $alertData);
        }

        if ($result) {
            return [RESULT_SUCCESS, '价格提醒设置成功'];
        } else {
            return [RESULT_ERROR, '价格提醒设置失败'];
        }
    }

    /**
     * 获取价格提醒列表
     */
    public function getPriceAlertList($data = [], $paginate = DB_LIST_ROWS)
    {
        // 验证参数
        if (empty($data['user_id'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        $where = [
            'user_id' => $data['user_id'],
            'is_active' => 1
        ];
        
        // 设置关联查询
        $this->modelPriceAlert->alias('pa');
        $this->modelPriceAlert->join = [
            ['product p', 'p.id = pa.product_id', 'LEFT'],
            [SYS_DB_PREFIX . 'picture pic', 'pic.id = p.cover_id', 'LEFT']
        ];

        $field = 'pa.*, p.name, p.specification, p.market_price, pic.path as cover';
        $order = 'pa.create_time desc';

        $list = $this->modelPriceAlert->getList($where, $field, $order, $paginate);

        return [RESULT_SUCCESS, '获取成功', $list];
    }

    /**
     * 删除价格提醒
     */
    public function deletePriceAlert($data = [])
    {
        // 验证参数
        if (empty($data['user_id']) || empty($data['alert_id'])) {
            return [RESULT_ERROR, '参数错误'];
        }

        $where = [
            'id' => $data['alert_id'],
            'user_id' => $data['user_id']
        ];

        $result = $this->modelPriceAlert->deleteInfo($where);
        if ($result !== false) {
            return [RESULT_SUCCESS, '删除成功'];
        } else {
            return [RESULT_ERROR, '删除失败'];
        }
    }
}
